package com.monkeyboy.mytest.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 作用：
 * cookie工具类
 * @author Gavin
 * @time:2018年10月5日
 */
@Slf4j
public class CookieUtil {
	/**
	 *作用：
	 * 根据cookie的键来或者值
	 * @Author:Gavin
	 * @time:2018年10月5日
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request,String cookieName) {
		String value=null;
		Cookie[] cookieList=request.getCookies();
		if(cookieList==null||cookieName==null) {
			return null;
		}
		try {
			for(int i=0;i<cookieList.length;i++) {
				if(cookieName.equals(cookieList[i].getName())) {
					value=URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
				}
			}
		} catch (Exception e) {
			log.error("\n获取cookie出错",e);
		}
		return value;
	}
	
	/**
	 *作用：
	 * 设置一个cookie
	 * @Author:Gavin
	 * @time:2018年10月5日
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 * @param domainName
	 * @param cookieTime
	 */
	public static boolean setCookie(HttpServletRequest request,HttpServletResponse response,
			String cookieName,String cookieValue,String domainName,int cookieTime) {
		boolean flag=true;
		try {
			if(cookieName==null||cookieName.length()<=0||cookieValue==null||cookieValue.length()<=0) {
				flag=false;
				return flag;
			}
			cookieValue=URLEncoder.encode(cookieValue, "UTF-8");
			Cookie cookie=new Cookie(cookieName,cookieValue);
			if(cookieTime>0) {
				cookie.setMaxAge(cookieTime);
			}
			cookie.setHttpOnly(true);//防止cookie被劫持
			if(domainName==null||domainName.length()<=0) {
				cookie.setDomain(".qupingce.com");
			}else {
				cookie.setDomain(domainName);
			}
			cookie.setPath("/");
			response.addCookie(cookie);
		} catch (Exception e) {
			log.error("\n设置cookie失败",e);
			flag=false;
		}
		return flag;
	}
	/**
	 *作用：
	 * 删除一个cookie
	 * @Author:Gavin
	 * @time:2018年10月5日
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param doMainName
	 * @return
	 */
	public static boolean delCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,String doMainName) {
		boolean flag=true;
		try {
			Cookie[] cookies=request.getCookies();
			if(cookies!=null) {
				for(Cookie cookie:cookies) {
					if(cookieName.equals(cookie.getName())) {
						if(doMainName==null) {
							cookie.setDomain(".qupingce.com");
						}else {
							cookie.setDomain(doMainName);
						}
						cookie.setPath("/");
						cookie.setMaxAge(0);
						response.addCookie(cookie);
						break;
					}
				}
			}
		} catch (Exception e) {
			log.error("\n删除cookie失败",e);
			flag=false;
		}
		return flag;
	}
}
